//
//  BGWFBuDeProductController.m
//  bigMall
//
//  Created by ios on 16/8/15.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGWFBuDeProductController.h"
#import "BGMyTenderCell.h"
#import "BGDateResult.h"
#import "BGOwnGoodsListModel.h"
#import "BGOwnBidLogModel.h"
#import "BGOwnGoodsDelModel.h"
#import "BGOwnGoodsDownModel.h"
#import "BGSellerReturnMaginModel.h"
#import "BGFaBuViewController.h"

@interface BGWFBuDeProductController () <UITableViewDelegate,UITableViewDataSource> {
    
    UITableView *_tableView;
    NSMutableArray *_dataArr;
    int index;
    UIImageView *imageView;
    UILabel *lable;
    NSString *typeStr;
    
}

@end

@implementation BGWFBuDeProductController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我发布的商品";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"";
    self.navigationItem.backBarButtonItem = back;
    
    [self initDat];
    
    [self createUI];
    
}

- (void)initDat {
    
    _dataArr = [NSMutableArray array];

}

- (void)createUI {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, BGWidth, BGHight) style:UITableViewStyleGrouped];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:_tableView];
    
    //刷新的加载
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addIndex)];
    
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(index)];
    
    [_tableView.header beginRefreshing];
    
    [self initDat];
    
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake((BGWidth - 70 ) / 2 + 10, (_tableView.height - 109 - 160) / 3, 70, 90)];
    imageView.image = [UIImage imageNamed:@"抱歉~暂无数据"];
    
    lable = [[UILabel alloc] initWithFrame:CGRectMake((BGWidth - 120 ) / 2 + 10, imageView.bottom + 21, 120, 16)];
    lable.text = @"抱歉~暂无数据";
    lable.font = [UIFont systemFontOfSize:16];
    [_tableView addSubview:lable];
    
    [_tableView addSubview:imageView];
    lable.hidden = YES;
    imageView.hidden = YES;
    
}
- (void)addIndex {
    
    index++;
//    [_dataArr removeAllObjects];
    [self loadInter];
    
}
- (void)index {
    
    index = 1;
    [_dataArr removeAllObjects];
    [self loadInter];
    
}
- (void)loadInter {
    
    [BGDateResult ownGoodsListOrder:@"id" thisPage:[NSString stringWithFormat:@"%d",index] pageNum:@"10" success:^(NSObject *result) {
        
                BGOwnGoodsListModel *model = [[BGOwnGoodsListModel alloc] init];
                model = (BGOwnGoodsListModel *)result;
                NSArray *listArr = [NSArray arrayWithArray:model.list];
                for (BGOwnBidLogValueModel *model in listArr) {
                    [_dataArr addObject:model];
                }
                //        _dataArr = listArr;
        if (_dataArr.count == 0 && index == 1) {
            
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshingWithNoMoreData];
            
            //判断数据源有无
            
            lable.hidden = NO;
            imageView.hidden = NO;
            
            
        }
        
        if (listArr.count == 0) {
            [_tableView.footer endRefreshingWithNoMoreData];
            return;
        }

                lable.hidden = YES;
                imageView.hidden = YES;
                [_tableView.footer endRefreshing];
                [_tableView.header endRefreshing];
                [_tableView reloadData];
                
            } failure:^(NSError *error) {
                
            }];
    
}

#pragma mark - delegate - 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 125;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView registerNib:[UINib nibWithNibName:@"BGMyTenderCell" bundle:nil] forCellReuseIdentifier:@"celId"];
    BGMyTenderCell *cel = [tableView dequeueReusableCellWithIdentifier:@"celId" forIndexPath:indexPath];
    cel.shangpinzongjia.text = @"商品总价：";
    cel.maipanzongliang.text = @"卖盘总量：";
    cel.faburiqi.text = @"发布日期：";
    
    BGOwnBidLogValueModel *model = [[BGOwnBidLogValueModel alloc] init];
    if (_dataArr.count != 0) {
        
        model = _dataArr[indexPath.row];
        
        switch ([model.status intValue]) {
            case -1:
                typeStr = @"准备资料";
                break;
            case 0:
                typeStr = @"待审核";
                break;
            case 1:
                typeStr = @"审核通过";
                break;
            case 2:
                typeStr = @"审核失败";
                break;
            case 3:
                typeStr = @"已下架";
                break;
            case 4:
                typeStr = @"已售空";
                break;
            default:
                break;
        }
        
        cel.bianhao.text = model.title;
        cel.toubiaojiage.text = model.total_price;
        cel.toubiaozongliang.text = model.number;
        cel.zhuangtai.text = typeStr;
        NSDate *dat = [NSDate dateWithTimeIntervalSince1970:[model.add_time intValue]];
        NSDateFormatter*df = [[NSDateFormatter alloc]init];
        [df setDateFormat:@"yyyy-MM-dd"];
        NSString *str = [df stringFromDate:dat];
        cel.toubiaoshijian.text =  str;

        
    }

    return cel;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    BGFaBuViewController *a = [[BGFaBuViewController alloc] init];
    BGOwnBidLogValueModel *model = [[BGOwnBidLogValueModel alloc] init];
//
    if (_dataArr.count != 0) {
        
        model = _dataArr[indexPath.row];
        
        [BGFaBuViewController share].goodsId = model.idStr;
        [BGFaBuViewController share].catId = model.cat_id;
        [BGFaBuViewController share].status = model.status;
        
        if ([model.status isEqualToString:@"3"]) {
            [self showMessage:@"该商品已经下架!"];
        }
        else if ([model.status isEqualToString:@"4"]) {
            [self showMessage:@"该商品已经售空!"];
        }
        else {
            self.hidesBottomBarWhenPushed = YES;
            [BGFaBuViewController share].type = @"WFB";
            
            [self.navigationController pushViewController:[BGFaBuViewController share] animated:YES];
        }
        NSLog(@"self.status === %@",model.status);
    }

}
//编辑的样式
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BGOwnBidLogValueModel *model = [[BGOwnBidLogValueModel alloc] init];
    if (_dataArr != 0) {
        
        model = _dataArr[indexPath.row];
        
    }
    // 删除的按钮
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
       
        
        //网络的删除
        [BGDateResult ownGoodsDelWithGoodsId:model.idStr success:^(NSObject *result) {
            
            BGOwnGoodsDelModel *a = [[BGOwnGoodsDelModel alloc] init];
            a = (BGOwnGoodsDelModel *)result;
            if ([a.status isEqualToString:@"1"]) {
                [self showMessage:a.msg];
                [self index];
            }else {
                [self showMessage:a.msg];
            }
            
        } failure:^(NSError *error) {
        }];
        
        // 1. 更新数据
        NSArray *indexPaths = @[indexPath]; // 构建 索引处的行数 的数组
        
        [_dataArr removeObjectAtIndex:indexPath.row];
        
        [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:(UITableViewRowAnimationLeft)];
        // 2. 更新UI
//        [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationLeft)];
    }];
    
    /// 下架的按钮
    UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"下架"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"点击了下架");
        
       //网络的下架
        NSLog(@"%@",model.idStr);
       [BGDateResult ownGoodsDownWithGoodsId:model.idStr success:^(NSObject *result) {
           
           BGOwnGoodsDownModel *a = [[BGOwnGoodsDownModel alloc] init];
           a = (BGOwnGoodsDownModel *)result;
           if ([a.status isEqualToString:@"1"]) {
               [self showMessage:a.msg];
               [self index];
           }else {
               [self showMessage:a.msg];
           }

           
       } failure:^(NSError *error) {
           
       }];
        
        // 1. 更新数据
        
        // 2. 更新UI
       
    }];
    topRowAction.backgroundColor = [UIColor blueColor];
    
    // 退还保证金
    UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"退还保证金"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"点击退还保证金");
        [BGDateResult returnMarginSellerWithGoosId:model.idStr success:^(NSObject *result) {
            
            BGSellerReturnMaginModel *a = [[BGSellerReturnMaginModel alloc] init];
            a = (BGSellerReturnMaginModel *)result;
            if ([a.status isEqualToString:@"1"]) {
                [self showMessage:a.msg];
                [self index];
            }else {
                [self showMessage:a.msg];
            }
            
        } failure:^(NSError *error) {
            
        }];
        
    }];
    moreRowAction.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    
    // 将设置好的按钮放到数组中返回
    if ([model.status intValue] == -1 || [model.status intValue] == 0 || [model.status intValue] == 1 || [model.status intValue] == 2 || [model.status intValue] == 4) {
        
        return @[topRowAction];
        
    } else {
        
        if ([model.publish_type isEqualToString:@"2"] && ![model.is_backed isEqualToString:@"1"]) {
            return @[moreRowAction];
        }else {
            return @[deleteRowAction];
        }
        
        
    }
}
- (void)showMessage:(NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    [self index];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
